import {
	baseURL
} from './base.js'; //导入接口的前缀地址
import store from '../store/index.js';


function userLogin() {
	return new Promise((resolve, reject) => {
		uni.login({
			provider: 'weixin',
			onlyAuthorize: true,
			success: function(loginRes) {
				uni.request({
					url: baseURL + 'mini/auth',
					method: 'POST',
					data: {
						code: loginRes.code
					},
					header: {
						Accept: 'application/json'
					},
					success: (res) => {
						let data = res.data;
						if (data.code === 200) {
							let userdata = data.body;
							if (userdata.user) {
								store.commit('setUserinfo', userdata.user);
								store.commit('setUsertoken', userdata.user.token);
								// 登录成功后 resolve
								resolve();
							} else {
								reject(new Error('未能获取用户信息'));
							}
						} else {
							reject(new Error('登录请求失败：' + data.message));
						}
					},
					fail: (err) => {
						reject(err);
					},
				});
			},
			fail: function(err) {
				reject(err);
			},
		});
	});
}
let pendingRequests = []; // 存储等待重试的请求
function processPendingRequests() {
  if (pendingRequests.length > 0) {
    const lastRetryRequest = pendingRequests.pop();
    myRequest(lastRetryRequest.options)
      .then((response) => {
        lastRetryRequest.resolve(response);
      })
      .catch((error) => {
        lastRetryRequest.reject(error);
        // 可能需要在这里做些额外的错误处理或通知用户
      });
  }
}

export const myRequest = (options) => {
	return new Promise((resolve, reject) => {
		//判断 token
		let requsttoken = options.type == 'shop' ? uni.getStorageSync('shoptoken') : options.type ==
			'employee' ? uni.getStorageSync('employeetoken') : uni.getStorageSync('usertoken');
		pendingRequests.push({
			options: options,
			resolve: resolve,
			reject: reject,
		});
		uni.request({
			url: baseURL + options.url, //接口地址：前缀+方法中传入的地址
			method: options.method || 'GET', //请求方法：传入的方法或者默认是“GET”
			data: options.data || {}, //传递参数：传入的参数或者默认传递空集合 
			header: {
				authorization: 'Bearer ' + requsttoken, //自定义请求头信息 
				Accept: 'application/json'
			},
			success: (res) => {
				if (res.statusCode == 401) {
					if (options.type == 'shop') {
						uni.removeStorageSync('shopinfo');
						uni.removeStorageSync('shoptoken');
						store.commit('setShopinfo', '');
						store.commit('setShoptoken', '');
						uni.reLaunch({
							url: '/pages/main/main'
						})
					} else if (options.type == 'employee') {
						uni.removeStorageSync('employeeinfo');
						uni.removeStorageSync('employeetoken');
						store.commit('setEmployeeinfo', '');
						store.commit('setEmployeetoken', '');
						uni.reLaunch({
							url: '/pages/main/main'
						})
					} else {
						userLogin().then(() => {
							  processPendingRequests();
						});
					}
				}else{
					console.log(res.data,'+++++++++++')
					resolve(res.data);
				}
				
			},
			// 这里的接口请求，如果出现问题就输出接口请求失败
			fail: (err) => {
				console.log(err)
				uni.showToast({
					title: '获取失败',
					icon: 'none'
				})
				reject(err)
			}
		})
	})
}
export const Login = () => {
	return userLogin();
}